package cn.edu.sjtu.se.dslab.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.sjtu.se.dslab.auth.CommonVariableModel;
import cn.edu.sjtu.se.dslab.auth.User;
import cn.edu.sjtu.se.dslab.dao.IUserDao;
import cn.edu.sjtu.se.dslab.service.IAuthService;
import cn.edu.sjtu.se.dslab.util.ClassParser;
import cn.edu.sjtu.se.dslab.util.Message;
/**
 * 需要重写
 * @author sunke
 *
 */
@Controller
public class LoginController {

	@Resource(name = "authService")
	IAuthService authService;
	
	@Resource(name = "userDao")
	IUserDao userDao;

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {

		Subject user = SecurityUtils.getSubject();
		if (user!= null) {
			CommonVariableModel model = (CommonVariableModel) user.getPrincipals()
					.getPrimaryPrincipal();
			System.out.println("close projectId:"+model.getProjectId());
		}
		user.logout();
		return "redirect:/login";
	}

	@RequestMapping(value = "/unauthorized", method = RequestMethod.GET)
	public ModelAndView unauthorizedPage() {
		// set view
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/unauthorized");

		return mav;
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView getLoginPage() {
		// set view
		ModelAndView mav = new ModelAndView();
		mav.setViewName("login");
		return mav;
	}

	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView registerPage() {
		// set view
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/register");
		return mav;
	}

	@RequestMapping(value = "/register/submit", method = RequestMethod.POST)
	public ModelAndView register(@RequestParam String username,
			@RequestParam String password, @RequestParam String email,
			@RequestParam String staffnum, @RequestParam String realname) {
		User temp = authService.getUserByUsername(username);
		ModelAndView mav = new ModelAndView();
		if (temp != null) {
			mav.setViewName("/register");
			mav.addObject("errormsg", "该用户名已经被注册，请更换");
			return mav;
		}
		User user = new User();
		user.setEmail(email);
		user.setUsername(username);
		user.setPassword(password);
		user.setRealname(realname);
		user.setStaffNum(staffnum);
		if (authService.register(user)) {
			mav.setViewName("login");
			return mav;
		} else {
			mav.setViewName("/register");
			return mav;
		}
	}

	@RequestMapping(value="/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
    	Subject user = SecurityUtils.getSubject();
    	UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    	token.setRememberMe(false);
    	try {
    		user.login(token);   		
    		return "redirect:/home";
    	} catch (AuthenticationException ae) {
    		System.out.println("登陆信息错误：" + ae);
    		token.clear();
    		return "redirect:/login";
    	}
    }
	
	@RequestMapping(value = "/login/rest", method = RequestMethod.POST)
	@ResponseBody
	public String loginByREST(String username,String password) {
		User result = authService.getUserByUsername(username);
		if (result != null) {
			String temp = new SimpleHash("MD5", password).toHex();
			if (temp!= null && temp.equals(result.getPassword())) {
				result.setGroupsList(null);
				result.setPermsList(null);
				result.setpGroups(null);
				ClassParser parser = new ClassParser();
				return parser.user2String(result);
			}
		}
			return Message.USER_NOT_EXISTS;
	}
}
